<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import layout from './views/layout/index.vue'
import useDataStore from './store';
import { storeToRefs } from 'pinia';
import { getPushingMessageAPI } from '@/apis/home'



defineOptions({
  name: 'App'
})

onMounted(() => {
  // console.log('agent', window.navigator.userAgent.toLowerCase());
  detectDeviceType()
  setupSSE()
})

// 销毁时关闭连接
onUnmounted(() => {
  if (eventSource.value) {
    eventSource.value.close()
  }
})


const dataStore = useDataStore()
const { userInfo, messageList } = storeToRefs(dataStore)

let eventSource = ref(null)   //SSE连接对象
let messageDataList = ref([]) //消息列表
let isMobile = ref(false) // 是否移动端设备

/* --------------------------------- 建立sse连接 -------------------------------- */
const setupSSE = () => {
  let token = localStorage.getItem('token') || ''
  // let userInfo = JSON.parse(localStorage.getItem('userInfo')) || {}
  // 发起连接
  eventSource.value = new EventSource(`/api/SSEMessage?token=${encodeURIComponent(token)}&user_id=${userInfo.value?.user_id}`);
  // eventSource.value = new EventSource(`http://8.138.1.3:8889/api/SSEMessage?token=${encodeURIComponent(token)}&user_id=${userInfo.value?.user_id}`);
  // 监听消息返回事件
  eventSource.value.onmessage = (event) => {
    messageDataList.value = JSON.parse(event.data);
    // console.log('messageDataList', messageDataList.value);
    dataStore.setMessageList(messageDataList.value)
    if (messageDataList.value.length) {
      ElNotification({
        title: '提示',
        message: "您有一条新的消息！",
        position: 'bottom-right',
        type: 'warning',
      })
    }

  };

}

/* -------------------------------- 判断当前设备类型 -------------------------------- */
const detectDeviceType = () => {
  const userAgent = window.navigator.userAgent.toLowerCase();
  const mobileRegex = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i;
  dataStore.setDeviceType(mobileRegex.test(userAgent))
};




</script>

<template>
    <router-view></router-view>
</template>

<style scoped lang='scss'></style>